package branice.spring.cloud.service.impl;

import branice.spring.cloud.service.NacosServerService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static branice.spring.cloud.constants.GlobalConstants.X_ID;

@Service
public class NacosServerServiceImpl implements NacosServerService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public JSONObject sendReq(String logId, String body) {
//        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos");
        String url = "http://nacos-consumer/nacosClient/reciveReq";

        HttpHeaders headers = new HttpHeaders();
        headers.add(X_ID, logId);

        HttpEntity entity = new HttpEntity(body,headers);

        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class);

        return exchange.getBody();
    }
}
